package com.yst.sqlbuilder;

import com.yst.lambda.TableFieldFunc;


public class SQLFieldBetween<T,V> extends SQLFieldExp<T> implements ISQLFieldExpression<T> {

    private final V value1;

    private final V value2;

    public SQLFieldBetween(IAliasExpression tableAlias, TableFieldFunc<T, ?> field, V value1, V value2) {
        super(tableAlias, field);
        this.value1=value1;
        this.value2=value2;
    }

    public SQLFieldBetween(TableFieldFunc<T, ?> field, IAliasExpression tableAlias, V value1, V value2) {
        super(field, tableAlias);
        this.value1=value1;
        this.value2=value2;
    }

    @Override
    public String generateExpression(GenerateParam param) {
        String valueFormat="'%s'";
        if (value1 instanceof SQLParam){
            valueFormat="%s";
            return getRealField().concat(" ")
                    .concat(Symbol.BETWEEN.symbol).concat(" ")
                    .concat(String.format(valueFormat, ((SQLParam<?>) value1).generateExpression(param)))
                    .concat(" AND ").concat(String.format(valueFormat, ((SQLParam<?>) value2).generateExpression(param)));
        }

        if (value1 instanceof Number||value1 instanceof Boolean){
            valueFormat="%s";
        }

        SQLSafe.getInstance().checkValue(value1.toString());
        SQLSafe.getInstance().checkValue(value2.toString());
        return getRealField().concat(" ")
                .concat(Symbol.BETWEEN.symbol).concat(" ")
                .concat(String.format(valueFormat, value1))
                .concat(" AND ").concat(String.format(valueFormat, value2));
    }
}
